package indi.zn.commons.math;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 排列 A(n,m)
 * 
 * @author zn
 */
public class Permutation<T> {

	private List<T> content;

	public Permutation(List<T> content) {

		this.content = content;

	}

	public List<ArrayList<T>> fullPermutation() {
		return permutation(content.size());
	}

	public List<ArrayList<T>> permutation(Integer c) {

		if (c <= content.size()) {

			List<ArrayList<T>> res = new ArrayList<ArrayList<T>>();
			ArrayList<T> arr = new ArrayList<T>(c);

			for (int i = 0; i < c; i++) {

				arr.add(content.get(i));

			}

			LinkedList<T> ll = new LinkedList<T>(content);

			perm(0, c, arr, ll, res);

			return res;
		} else {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	private void perm(Integer s, Integer c, ArrayList<T> arr, LinkedList<T> ll, List<ArrayList<T>> res) {

		for (int i = 0; i < ll.size(); i++) {

			arr.set(s, ll.get(i));

			if (s < c - 1) {

				LinkedList<T> ll$ = new LinkedList<T>(ll);
				ll$.remove(i);

				perm(s + 1, c, arr, ll$, res);

			} else {

				res.add((ArrayList<T>) arr.clone());

			}
		}

	}
	
}
